package com.gewu.pm.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/**
 * 字母索引侧边栏
 */
public class SideBarView extends View {
    private static final String[] LETTERS = {
        "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
        "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
        "W", "X", "Y", "Z"
    };

    private OnLetterChangeListener mListener;
    private int mCurrentIndex = -1;

    public SideBarView(Context context) {
        super(context);
    }

    public SideBarView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SideBarView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setOnLetterChangeListener(OnLetterChangeListener listener) {
        this.mListener = listener;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        int width = getWidth();
        int height = getHeight();
        int singleHeight = height / LETTERS.length;

        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setTextSize(24);

        for (int i = 0; i < LETTERS.length; i++) {
            // 所有字母都是红色
            paint.setColor(0xFFFF0000); // 红色
            float x = width / 2f - paint.measureText(LETTERS[i]) / 2;
            float y = singleHeight * i + singleHeight / 2f + paint.getTextSize() / 3;
            canvas.drawText(LETTERS[i], x, y, paint);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        float y = event.getY();
        int index = (int) (y / getHeight() * LETTERS.length);

        switch (action) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
                if (index >= 0 && index < LETTERS.length && index != mCurrentIndex) {
                    mCurrentIndex = index;
                    if (mListener != null) {
                        mListener.onLetterChange(LETTERS[index]);
                    }
                    invalidate();
                }
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                mCurrentIndex = -1;
                if (mListener != null) {
                    mListener.onLetterTouchEnd();
                }
                invalidate();
                break;
        }
        return true;
    }

    public interface OnLetterChangeListener {
        void onLetterChange(String letter);
        void onLetterTouchEnd();
    }
}
